package com.gxuwz.weather.fragment;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import com.gxuwz.weather.MainActivity;
import com.gxuwz.weather.R;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.gxuwz.weather.api.Weather7dRequest;
import com.gxuwz.weather.api.Weather15dRequest;
import android.util.Log;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.gxuwz.weather.api.RealTimeRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.util.TypedValue;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import com.gxuwz.weather.db.CityDao;
import android.content.Intent;
import com.gxuwz.weather.CityManageActivity;
import com.airbnb.lottie.LottieAnimationView;
import android.widget.FrameLayout;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import org.json.JSONObject;
import org.json.JSONException;

public class WeatherFragment extends Fragment {
    private static final String ARG_CITY = "city";
    private static final String ARG_IS_PREVIEW = "is_preview";
    private String city;
    private boolean isPreview = false;

    // 声明新的TextViews
    private TextView tvCityName;
    private TextView tvCurrentTemperature;
    private TextView tvWeatherCondition;
    private TextView tvHighLowTemperature;
    private TextView tvAirQualityValue;
    private TextView tvAirQualityDesc;
    private TextView tvWindDirectionSpeed;
    private TextView tvWindSpeedValue;
    private TextView tvFeelsLikeValue;
    private TextView tvFeelsLikeDesc;
    private TextView tvHumidityValue;
    private TextView tvHumidityDesc;
    private TextView tvVisibilityValue;
    private TextView tvVisibilityDesc;
    private TextView tvPressureValue;
    private TextView tvPressureUnit;
    private TextView tvPressureDesc;
    private TextView tvPrecipitationValue;
    private TextView tvPrecipitationDesc;
    private LinearLayout hourlyWeatherContainer;
    private CardView cardWarning; // 声明 CardView
    private TextView tvWarningTitle;
    private TextView tvWarningContent;
    private LinearLayout llViewMore;
    private LinearLayout bottomNavigationBar; // 声明底部导航栏

    private CityDao cityDao;

    private FrameLayout loadingLayerWeather;

    // 定义一个私有内部类来表示要显示的项目
    private class DisplayItem implements Comparable<DisplayItem> {
        String type; // "weather", "sunrise", "sunset"
        String displayTime; // "14时", "05:47"
        String displayValue; // "30°", "日出", "日落"
        String iconCode; // "1", "sunup", "sundown"
        LocalDateTime actualDateTime; // 用于精确排序

        public DisplayItem(String type, String displayTime, String displayValue, String iconCode, LocalDateTime actualDateTime) {
            this.type = type;
            this.displayTime = displayTime;
            this.displayValue = displayValue;
            this.iconCode = iconCode;
            this.actualDateTime = actualDateTime;
        }

        @Override
        public int compareTo(DisplayItem other) {
            return this.actualDateTime.compareTo(other.actualDateTime);
        }
    }

    public static WeatherFragment newInstance(String city) {
        return newInstance(city, false);
    }

    public static WeatherFragment newInstance(String city, boolean isPreview) {
        WeatherFragment fragment = new WeatherFragment();
        Bundle args = new Bundle();
        args.putString(ARG_CITY, city);
        args.putBoolean(ARG_IS_PREVIEW, isPreview);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            city = getArguments().getString(ARG_CITY);
            isPreview = getArguments().getBoolean(ARG_IS_PREVIEW, false);
        }
        // 初始化数据库操作类
        cityDao = new CityDao(requireContext());
        cityDao.open();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (cityDao != null) {
            cityDao.close();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_weather, container, false);

        // 初始化视图
        tvCityName = view.findViewById(R.id.tvCityName);
        tvCurrentTemperature = view.findViewById(R.id.tvCurrentTemperature);
        tvWeatherCondition = view.findViewById(R.id.tvWeatherCondition);
        tvHighLowTemperature = view.findViewById(R.id.tvHighLowTemperature);
        tvAirQualityValue = view.findViewById(R.id.tvAirQualityValue);
        tvAirQualityDesc = view.findViewById(R.id.tvAirQualityDesc);
        tvWindDirectionSpeed = view.findViewById(R.id.tvWindDirectionSpeed);
        tvWindSpeedValue = view.findViewById(R.id.tvWindSpeedValue);
        tvFeelsLikeValue = view.findViewById(R.id.tvFeelsLikeValue);
        tvFeelsLikeDesc = view.findViewById(R.id.tvFeelsLikeDesc);
        tvHumidityValue = view.findViewById(R.id.tvHumidityValue);
        tvHumidityDesc = view.findViewById(R.id.tvHumidityDesc);
        tvVisibilityValue = view.findViewById(R.id.tvVisibilityValue);
        tvVisibilityDesc = view.findViewById(R.id.tvVisibilityDesc);
        tvPressureValue = view.findViewById(R.id.tvPressureValue);
        tvPressureUnit = view.findViewById(R.id.tvPressureUnit);
        tvPressureDesc = view.findViewById(R.id.tvPressureDesc);
        tvPrecipitationValue = view.findViewById(R.id.tvPrecipitationValue);
        tvPrecipitationDesc = view.findViewById(R.id.tvPrecipitationDesc);
        hourlyWeatherContainer = view.findViewById(R.id.hourlyWeatherContainer);
        cardWarning = view.findViewById(R.id.cardWarning); // 初始化 CardView
        tvWarningTitle = view.findViewById(R.id.tvWarningTitle);
        tvWarningContent = view.findViewById(R.id.tvWarningContent);
        llViewMore = view.findViewById(R.id.llViewMore);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        bottomNavigationBar = view.findViewById(R.id.bottom_navigation_bar); // 初始化底部导航栏
        Log.d("WeatherFragment", "Bottom navigation bar initialized in onViewCreated: " + (bottomNavigationBar != null));

        // 初始化并显示加载动画层
        loadingLayerWeather = view.findViewById(R.id.loading_layer_weather);
        if (loadingLayerWeather != null) {
            loadingLayerWeather.setVisibility(View.VISIBLE);
        }
        // 隐藏内容区
//        if (tvCityName != null) tvCityName.setVisibility(View.INVISIBLE);
//        if (tvCurrentTemperature != null) tvCurrentTemperature.setVisibility(View.INVISIBLE);
//        if (tvWeatherCondition != null) tvWeatherCondition.setVisibility(View.INVISIBLE);
        // 只有有效城市名时才请求天气
        if (city != null && !city.isEmpty()) {
            if (!"LOADING".equals(city)) {
                if (isPreview) {
                    fetchWeatherData(city);
                } else {
                    loadSavedCities();
                }
            }
        }
    }

    private boolean isLocationCity(String cityName) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
        String gpsCity = prefs.getString("gps_city", "");
        return cityName != null && !cityName.isEmpty() && cityName.equals(gpsCity);
    }

    private boolean isFirstPageLocationCity() {
        // 如果本Fragment是ViewPager的第一个页面（即定位城市）
        return getArguments() != null && getArguments().getInt("position", -1) == 0;
    }

    private void loadSavedCities() {
        // 从数据库加载城市列表
        List<String> cities = cityDao.getAllCities();
        int position = getArguments() != null ? getArguments().getInt("position", -1) : -1;
        if (position == 0) {
            // 第一个页面（定位城市），无论currentCity如何都允许显示
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
            String lat = prefs.getString("gps_lat", "");
            String lng = prefs.getString("gps_lng", "");
            if (!lat.isEmpty() && !lng.isEmpty()) {
                fetchWeatherDataByLatLng(lat, lng);
            }
            // 经纬度为空时不再弹Toast，也不跳转，静默等待MainActivity定位完成后刷新
            return;
        }
        if (cities != null && !cities.isEmpty()) {
            // 获取当前选中的城市
            String currentCity = getArguments() != null ? getArguments().getString(ARG_CITY) : null;
            // 检查当前城市是否还在数据库中，或是定位城市（第一个页面）
            if (currentCity != null && !currentCity.isEmpty()) {
                if (cityDao.isCityExists(currentCity) || isLocationCity(currentCity)) {
                    fetchWeatherData(currentCity);
                } else {
                    // 只跳转，不finish Activity，避免App直接退出
                    Intent intent = new Intent(getActivity(), CityManageActivity.class);
                    startActivity(intent);
                }
            } else {
                // 只跳转，不finish Activity，避免App直接退出
                Intent intent = new Intent(getActivity(), CityManageActivity.class);
                startActivity(intent);
            }
        } else {
            // 只跳转，不finish Activity，避免App直接退出
            Intent intent = new Intent(getActivity(), CityManageActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isPreview) {
            fetchWeatherData(city);
            return;
        }
        // 获取当前选中的城市
        String currentCity = getArguments() != null ? getArguments().getString(ARG_CITY) : null;
        if (currentCity != null && !currentCity.isEmpty()) {
            // 检查城市是否还在数据库中
            if (cityDao.isCityExists(currentCity) || isLocationCity(currentCity)) {
                // 如果城市存在或是定位城市，获取该城市的天气
                fetchWeatherData(currentCity);
            } else {
                // 如果城市不存在，返回城市管理界面
                Intent intent = new Intent(getActivity(), CityManageActivity.class);
                startActivity(intent);
                if (getActivity() != null) {
                    getActivity().finish();
                }
            }
        } else {
            // 如果没有选中的城市，返回城市管理界面
            Intent intent = new Intent(getActivity(), CityManageActivity.class);
            startActivity(intent);
            if (getActivity() != null) {
                getActivity().finish();
            }
        }
    }

    private void fetchWeatherData(String city) {
        if (city == null || city.isEmpty()) {
            Toast.makeText(getContext(), "城市名称为空，无法获取天气数据", Toast.LENGTH_SHORT).show();
            // 加载失败也隐藏加载层
            if (loadingLayerWeather != null) loadingLayerWeather.setVisibility(View.GONE);
            return;
        }

        // 首先请求实时天气数据
        RealTimeRequest.getWeather(city, new RealTimeRequest.WeatherCallback() {
            @Override
            public void onSuccess(String temperature, String weather, String windDirection, String windSpeed, String aqi,
                                  String sunrise, String sunset, JsonArray hourlyData, JsonObject now, JsonObject day, JsonObject night, JsonObject data,JsonObject lifeIndex) {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        if (now != null && now.has("cityname")) tvCityName.setText(now.get("cityname").getAsString());
                        if (now != null && now.has("temp")) tvCurrentTemperature.setText(now.get("temp").getAsString() + "°");
                        if (now != null && now.has("weather")) {
                            String weatherCondition = now.get("weather").getAsString();
                            tvWeatherCondition.setText(weatherCondition);
                            // 根据天气状况设置背景
                            setWeatherBackground(weatherCondition);
                        }

                        // 更新日出日落
//                        if (tvSunriseTime != null) tvSunriseTime.setText("日出: " + sunrise);
//                        if (tvSunsetTime != null) tvSunsetTime.setText("日落: " + sunset);

                        // 更新空气质量
                        if (now != null && now.has("aqi")) {
                            int aqiValue = now.get("aqi").getAsInt();
                            tvAirQualityValue.setText(aqiValue + " - " + getAirQualityDesc(aqiValue));
                            tvAirQualityDesc.setText("当前 AQI (CN) 为 " + aqiValue + "。");
                        }

                        // 更新风向和风速
                        if (now != null) {
                            String windDir = now.has("WD") ? now.get("WD").getAsString() : "";
                            String windSpd = now.has("WS") ? now.get("WS").getAsString() : "";
                            String windScale = now.has("wse") ? now.get("wse").getAsString() : "";

                            if (tvWindDirectionSpeed != null) {
                                tvWindDirectionSpeed.setText(windDir + " "  + " (" + windSpd + ")");
                            }
                            if(tvWindSpeedValue != null){
                                tvWindSpeedValue.setText(windScale);
                            }

                        }

                        // 更新降雨
                        if (now != null && now.has("rain24h")) {
                            tvPrecipitationValue.setText(now.get("rain24h").getAsString() + " 毫米");
                            tvPrecipitationDesc.setText("过去 24 小时。"); // 简化描述，因为没有未来24小时降雨量数据
                        }

                        // 更新PM2.5浓度
                        if (now != null && now.has("aqi_pm25")) {
                            tvFeelsLikeValue.setText(now.get("aqi_pm25").getAsString());
                            tvFeelsLikeDesc.setText("空气质量指数PM2.5。"); // 适应PM2.5浓度卡片
                        }

                        // 更新湿度
                        if (now != null && now.has("SD")) {
                            tvHumidityValue.setText(now.get("SD").getAsString());
                            tvHumidityDesc.setText("目前露点温度为 25°。"); // 默认描述，可以根据实际数据调整
                        }

                        // 更新能见度
                        if (now != null && now.has("njd")) {
                            tvVisibilityValue.setText(now.get("njd").getAsString().replace("km", " 公里"));
                            tvVisibilityDesc.setText("目前非常晴朗。"); // 默认描述，可以根据实际数据调整
                        }

                        // 更新气压
                        if (now != null && now.has("qy")) {
                            tvPressureValue.setText(now.get("qy").getAsString() + "百帕");
//                            tvPressureUnit.setText("百帕");
//                            tvPressureDesc.setText("低 高"); // 默认描述，可以根据实际数据调整
                        }

                        //最高气温和最低气温
                        if (day != null && night != null && tvHighLowTemperature != null) {
                            String maxTemp = day.get("temperature").getAsString();
                            String minTemp = night.get("temperature").getAsString();
                            tvHighLowTemperature.setText("最高 " + maxTemp + "° 最低 " + minTemp + "°");
                        }

                        // 更新紫外线指数 (示例数据中没有，这里暂时用硬编码)
//                        tvUVIndexValue.setText("2");
//                        tvUVIndexDesc.setText("低");

                                // 更新紫外线指数
                                if (lifeIndex.has("紫外线指数")) {
                                    JsonObject uvIndex = lifeIndex.getAsJsonObject("紫外线指数");
                                    TextView tvUvValue = getView().findViewById(R.id.tvUvValue);
                                    TextView tvUvDesc = getView().findViewById(R.id.tvUvDesc);
                                    if (tvUvValue != null && tvUvDesc != null) {
                                        tvUvValue.setText(uvIndex.get("state").getAsString());
                                        tvUvDesc.setText(uvIndex.get("reply").getAsString());
                                    }
                                }

                                // 更新穿衣指数
                                if (lifeIndex.has("穿衣指数")) {
                                    JsonObject clothingIndex = lifeIndex.getAsJsonObject("穿衣指数");
                                    TextView tvClothingValue = getView().findViewById(R.id.tvClothingValue);
                                    TextView tvClothingDesc = getView().findViewById(R.id.tvClothingDesc);
                                    if (tvClothingValue != null && tvClothingDesc != null) {
                                        tvClothingValue.setText(clothingIndex.get("state").getAsString());
                                        tvClothingDesc.setText(clothingIndex.get("reply").getAsString());
                                    }
                                }

                                // 更新运动指数
                                if (lifeIndex.has("运动指数")) {
                                    JsonObject sportIndex = lifeIndex.getAsJsonObject("运动指数");
                                    TextView tvSportValue = getView().findViewById(R.id.tvSportValue);
                                    TextView tvSportDesc = getView().findViewById(R.id.tvSportDesc);
                                    if (tvSportValue != null && tvSportDesc != null) {
                                        tvSportValue.setText(sportIndex.get("state").getAsString());
                                        tvSportDesc.setText(sportIndex.get("reply").getAsString());
                                    }
                                }

                                // 更新过敏指数
                                if (lifeIndex.has("过敏指数")) {
                                    JsonObject allergyIndex = lifeIndex.getAsJsonObject("过敏指数");
                                    TextView tvAllergyValue = getView().findViewById(R.id.tvAllergyValue);
                                    TextView tvAllergyDesc = getView().findViewById(R.id.tvAllergyDesc);
                                    if (tvAllergyValue != null && tvAllergyDesc != null) {
                                        String state = allergyIndex.get("state").getAsString();
                                        String reply = allergyIndex.get("reply").getAsString();
                                        tvAllergyValue.setText(state);
                                        tvAllergyDesc.setText(reply);
                                    }
                                }

                                // 更新感冒指数
                                if (lifeIndex.has("感冒指数")) {
                                    JsonObject coldIndex = lifeIndex.getAsJsonObject("感冒指数");
                                    TextView tvColdValue = getView().findViewById(R.id.tvColdValue);
                                    TextView tvColdDesc = getView().findViewById(R.id.tvColdDesc);
                                    if (tvColdValue != null && tvColdDesc != null) {
                                        tvColdValue.setText(coldIndex.get("state").getAsString());
                                        tvColdDesc.setText(coldIndex.get("reply").getAsString());
                                    }
                                }

                                // 更新洗车指数
                                if (lifeIndex.has("洗车指数")) {
                                    JsonObject carWashIndex = lifeIndex.getAsJsonObject("洗车指数");
                                    TextView tvCarWashValue = getView().findViewById(R.id.tvCarWashValue);
                                    TextView tvCarWashDesc = getView().findViewById(R.id.tvCarWashDesc);
                                    if (tvCarWashValue != null && tvCarWashDesc != null) {
                                        tvCarWashValue.setText(carWashIndex.get("state").getAsString());
                                        tvCarWashDesc.setText(carWashIndex.get("reply").getAsString());
                                    }
                                }


                        // ==== 预警信息逻辑开始 ====);
                        JsonArray alarmList = data != null && data.has("alarmList") ? data.getAsJsonArray("alarmList") : null;
                        if (alarmList != null && alarmList.size() > 0) {
                            cardWarning.setVisibility(View.VISIBLE); // 显示预警卡片

                            List<String> signalTypes = new ArrayList<>();
                            List<String> issueContents = new ArrayList<>();

                            for (int i = 0; i < alarmList.size(); i++) {
                                JsonObject alarm = alarmList.get(i).getAsJsonObject();
                                if (alarm.has("signalType")) {
                                    signalTypes.add(alarm.get("signalType").getAsString());
                                }
                                if (alarm.has("issueContent")) {
                                    issueContents.add(alarm.get("issueContent").getAsString());
                                }
                            }

                            // 设置标题：台风与暴雨
                            StringBuilder titleBuilder = new StringBuilder();
                            for (int i = 0; i < signalTypes.size(); i++) {
                                titleBuilder.append(signalTypes.get(i));
                                if (i < signalTypes.size() - 1) {
                                    titleBuilder.append("与");
                                }
                            }
                            tvWarningTitle.setText(titleBuilder.toString());

                            // 设置内容：国家预警信息发布中心：台风，暴雨。
                            StringBuilder contentBuilder = new StringBuilder("国家预警信息发布中心：");
                            for (int i = 0; i < signalTypes.size(); i++) {
                                contentBuilder.append(signalTypes.get(i));
                                if (i < signalTypes.size() - 1) {
                                    contentBuilder.append("，");
                                }
                            }
                            tvWarningContent.setText(contentBuilder.toString());

                            // 点击查看更多allergy
                            llViewMore.setOnClickListener(v -> {
                                Dialog dialog = new Dialog(requireContext());
                                dialog.setContentView(R.layout.dialog_allergy_detail);

                                // 设置弹窗宽度为屏幕的80%
                                Window window = dialog.getWindow();
                                if (window != null) {
                                    WindowManager.LayoutParams params = window.getAttributes();
                                    params.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.8);
                                    window.setAttributes(params);
                                    window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                                }

                                // 设置预警图标 (使用第一个预警的级别作为弹窗主图标)
                                ImageView ivWarningIcon = dialog.findViewById(R.id.iv_warning_icon);
                                int iconResId;
                                String mainLevel = "蓝色"; // 默认级别
                                if (alarmList.size() > 0 && alarmList.get(0).getAsJsonObject().has("signalLevel")) {
                                    mainLevel = alarmList.get(0).getAsJsonObject().get("signalLevel").getAsString();
                                }
                                switch (mainLevel) {
                                    case "蓝色":
                                        iconResId = R.drawable.icon_blue_allergy;
                                        break;
                                    case "黄色":
                                        iconResId = R.drawable.icon_yellow_allergy;
                                        break;
                                    case "橙色":
                                        iconResId = R.drawable.icon_orange_allergy;
                                        break;
                                    case "红色":
                                        iconResId = R.drawable.icon_red_allergy;
                                        break;
                                    default:
                                        iconResId = R.drawable.icon_blue_allergy;
                                }
                                ivWarningIcon.setImageResource(iconResId);

                                // 添加预警内容
                                LinearLayout container = dialog.findViewById(R.id.ll_warning_container);
                                container.removeAllViews(); // 清除之前的视图，确保不叠加

                                for (int i = 0; i < alarmList.size(); i++) {
                                    JsonObject alarm = alarmList.get(i).getAsJsonObject();
                                    View warningItem = getLayoutInflater().inflate(R.layout.item_warning, container, false);
                                    TextView tvTitle = warningItem.findViewById(R.id.tv_warning_title);
                                    TextView tvContent = warningItem.findViewById(R.id.tv_warning_content);

                                    String signalLevel = alarm.has("signalLevel") ? alarm.get("signalLevel").getAsString() : "无级别";
                                    String signalType = alarm.has("signalType") ? alarm.get("signalType").getAsString() : "未知类型";
                                    String issueTime = alarm.has("issueTime") ? alarm.get("issueTime").getAsString() : "未知时间";
                                    String issueContent = alarm.has("issueContent") ? alarm.get("issueContent").getAsString() : "无内容";

                                    tvTitle.setText(signalLevel + "预警 - " + signalType);
                                    tvContent.setText("发布时间：" + issueTime + "\n" + issueContent);

                                    container.addView(warningItem);
                                }

                                // 设置确定按钮
                                Button btnConfirm = dialog.findViewById(R.id.btn_confirm);
                                if (btnConfirm != null) {
                                    btnConfirm.setOnClickListener(v1 -> dialog.dismiss());
                                }

                                dialog.show();
                            });

                        } else {
                            cardWarning.setVisibility(View.GONE); // 没有预警信息时隐藏
                        }

                        updateHourlyWeather(hourlyData, sunrise, sunset, now); // 传递now对象

                        // 更新卡片颜色
                        updateCardColors(weather);

                        // 数据加载成功后隐藏加载层
                        if (loadingLayerWeather != null) loadingLayerWeather.setVisibility(View.GONE);
                    });
                }

                // 接着请求7日天气数据
                Weather7dRequest.requestWeather(city, new Weather7dRequest.Weather7dCallback() {
                    @Override
                    public void onSuccess(JsonObject weather7dData) {
                        // 请求15日天气数据
                        Weather15dRequest.requestWeather(city, new Weather15dRequest.Weather15dCallback() {
                            @Override
                            public void onSuccess(JsonObject weather15dData) {
                                // 合并7日和15日数据
                                JsonObject combinedWeatherData = new JsonObject();
                                if (weather7dData != null && weather7dData.has("data")) {
                                    combinedWeatherData.add("7d_data", weather7dData.getAsJsonObject("data"));
                                }
                                if (weather15dData != null && weather15dData.has("data")) {
                                    combinedWeatherData.add("15d_data", weather15dData.getAsJsonObject("data"));
                                }

                                // 在主线程更新UI
                                if (getActivity() != null) {
                                    getActivity().runOnUiThread(() -> {
                                        updateCombinedWeather(combinedWeatherData, now, day, night);
                                        Log.d("WeatherData", "Combined data: " + combinedWeatherData.toString());
                                    });
                                }
                            }

                            @Override
                            public void onError(String error) {
                                if (getActivity() != null) {
                                    getActivity().runOnUiThread(() -> {
                                        Toast.makeText(getContext(), "获取15日天气失败: " + error, Toast.LENGTH_SHORT).show();
                                        // 即使15日数据获取失败，也尝试显示7日数据
                                        if (weather7dData != null) {
                                            JsonObject tempCombinedData = new JsonObject();
                                            if (weather7dData.has("data")) {
                                                tempCombinedData.add("7d_data", weather7dData.getAsJsonObject("data"));
                                            }
                                            updateCombinedWeather(tempCombinedData, now, day, night);
                                            Log.e("WeatherError", "7d error: " + error); // 或 "15d error: " + error
                                        }
                                    });
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(String error) {
                        if (getActivity() != null) {
                            getActivity().runOnUiThread(() -> {
                                Toast.makeText(getContext(), "获取7日天气失败: " + error, Toast.LENGTH_SHORT).show();
                            });
                        }
                    }
                });
            }

            @Override
            public void onError(String error) {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "获取实时天气失败: " + error, Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }

    private void updateCombinedWeather(JsonObject combinedWeatherData, JsonObject now, JsonObject day, JsonObject night) {
        if (combinedWeatherData == null) return;

        JsonObject data7d = combinedWeatherData.getAsJsonObject("7d_data");
        JsonObject data15d = combinedWeatherData.getAsJsonObject("15d_data");
        if (data7d == null && data15d == null) return;

        // 获取天气容器
        LinearLayout dailyWeatherContainer = getView().findViewById(R.id.dailyWeatherContainer);
        if (dailyWeatherContainer == null) return;

        // 先遍历所有天，找到全周期最低温和最高温
        int minTemp = Integer.MAX_VALUE;
        int maxTemp = Integer.MIN_VALUE;
        List<JsonObject> allDays = new ArrayList<>();

        // 先加今天
        if (now != null && day != null && night != null) {
            JsonObject todayWeather = new JsonObject();
            todayWeather.addProperty("time", "今天");
            todayWeather.addProperty("weather", now.has("weather") ? now.get("weather").getAsString() : "");
            todayWeather.addProperty("day_weather_pic", now.has("weathercode") ? now.get("weathercode").getAsString() : "");
            todayWeather.addProperty("temperature_min", night.has("temperature") ? night.get("temperature").getAsString() : "");
            todayWeather.addProperty("temperature_max", day.has("temperature") ? day.get("temperature").getAsString() : "");
            allDays.add(todayWeather);
        }

        if (data7d != null) {
            for (int i = 2; i <= 7; i++) {
                String dayKey = "d" + i;
                if (data7d.has(dayKey)) {
                    JsonObject dayWeather = data7d.getAsJsonObject(dayKey);
                    if (dayWeather != null && dayWeather.has("temperature_min") && dayWeather.has("temperature_max")) {
                        String tminStr = dayWeather.get("temperature_min").getAsString().replaceAll("[^\\d-]", "");
                        String tmaxStr = dayWeather.get("temperature_max").getAsString().replaceAll("[^\\d-]", "");
                        int tmin = Integer.parseInt(tminStr);
                        int tmax = Integer.parseInt(tmaxStr);
                        if (tmin < minTemp) minTemp = tmin;
                        if (tmax > maxTemp) maxTemp = tmax;
                        allDays.add(dayWeather);
                    }
                }
            }
        }
        if (data15d != null) {
            for (int i = 8; i <= 15; i++) {
                String dayKey = "d" + i;
                if (data15d.has(dayKey)) {
                    JsonObject dayWeather = data15d.getAsJsonObject(dayKey);
                    if (dayWeather != null && dayWeather.has("temperature_min") && dayWeather.has("temperature_max")) {
                        String tminStr = dayWeather.get("temperature_min").getAsString().replaceAll("[^\\d-]", "");
                        String tmaxStr = dayWeather.get("temperature_max").getAsString().replaceAll("[^\\d-]", "");
                        int tmin = Integer.parseInt(tminStr);
                        int tmax = Integer.parseInt(tmaxStr);
                        if (tmin < minTemp) minTemp = tmin;
                        if (tmax > maxTemp) maxTemp = tmax;
                        allDays.add(dayWeather);
                    }
                }
            }
        }
        int tempRange = Math.max(1, maxTemp - minTemp); // 避免除0

        // 清除现有视图
        dailyWeatherContainer.removeAllViews();
        LayoutInflater inflater = LayoutInflater.from(getContext());

        // 重新渲染所有天
        for (JsonObject dayWeather : allDays) {
            View weatherItemView = inflater.inflate(R.layout.item_daily_weather, dailyWeatherContainer, false);

            // 时间
            TextView tvDate = weatherItemView.findViewById(R.id.tvDate);
            String time = dayWeather.has("time") ? dayWeather.get("time").getAsString() : "";
            if (time.contains("（") && time.contains("）")) {
                time = time.substring(time.indexOf("（") + 1, time.indexOf("）"));
            }
            tvDate.setText(time);

            // 天气状况
            TextView tvWeather = weatherItemView.findViewById(R.id.tvWeather);
            String weather = dayWeather.has("weather") ? dayWeather.get("weather").getAsString() : "";
            tvWeather.setText(weather);

            // 天气图标
            ImageView ivWeatherIcon = weatherItemView.findViewById(R.id.ivWeatherIcon);
            String weatherIcon = dayWeather.has("day_weather_pic") ? dayWeather.get("day_weather_pic").getAsString() : "";
            ivWeatherIcon.setImageResource(getWeatherIconResId(weatherIcon));

            // 最低温
            TextView tvTempMin = weatherItemView.findViewById(R.id.tvTempMin);
            String tminStr = dayWeather.get("temperature_min").getAsString().replaceAll("[^\\d-]", "");
            int tmin = tminStr.isEmpty() ? 0 : Integer.parseInt(tminStr);
            tvTempMin.setText(tmin + "°");

            // 最高温
            TextView tvTempMax = weatherItemView.findViewById(R.id.tvTempMax);
            String tmaxStr = dayWeather.get("temperature_max").getAsString().replaceAll("[^\\d-]", "");
            int tmax = tmaxStr.isEmpty() ? 0 : Integer.parseInt(tmaxStr);
            tvTempMax.setText(tmax + "°");

            // 温度条
            ProgressBar progressTemp = weatherItemView.findViewById(R.id.progressTemp);
            progressTemp.setMax(tempRange);
            progressTemp.setProgress(Math.max(0, tmax - tmin));

            // 风向和风力
            TextView tvWind = weatherItemView.findViewById(R.id.tvWind);
            TextView tvPow = weatherItemView.findViewById(R.id.tvPow);

            String wind = "";
            String windPow = "";

// 7天数据
            if (dayWeather.has("wind_day")) {
                wind = dayWeather.get("wind_day").getAsString();
                windPow = ""; // 7天没有风力
            }
// 15天数据
            else if (dayWeather.has("wind") && dayWeather.has("wind_pow")) {
                wind = dayWeather.get("wind").getAsString();
                windPow = dayWeather.get("wind_pow").getAsString();
            }

// 设置风向和风力显示
            if (!wind.isEmpty()) {
                tvWind.setText(wind);
                if (!windPow.isEmpty()) {
                    tvPow.setText("（" + windPow + "）");
                } else {
                    tvPow.setText("");
                }
            } else {
                tvWind.setText("");
                tvPow.setText("");
            }

            dailyWeatherContainer.addView(weatherItemView);
        }
    }

    private String getAirQualityDesc(int aqi) {
        if (aqi <= 50) return "优";
        if (aqi <= 100) return "良";
        if (aqi <= 150) return "轻度污染";
        if (aqi <= 200) return "中度污染";
        if (aqi <= 300) return "重度污染";
        return "严重污染";
    }

    // 根据天气代码获取对应的图标资源ID
    private int getWeatherIconResId(String weatherCode) {
        switch (weatherCode) {
            case "d00": // 晴
                return R.drawable.d00;
            case "d01": // 多云
                return R.drawable.d01;
            case "d02": // 阴
                return R.drawable.d02;
            case "d03": return R.drawable.d03;
            case "d04": return R.drawable.d04;
            case "d05": return R.drawable.d05;
            case "d06": return R.drawable.d06;
            case "d07": return R.drawable.d07;
            case "d08": return R.drawable.d08;
            case "d09": return R.drawable.d09;
            case "d10": return R.drawable.d10;
            case "d11": return R.drawable.d11;
            case "d12": return R.drawable.d12;
            case "d13": return R.drawable.d13;
            case "d14": return R.drawable.d14;
            case "d15": return R.drawable.d15;
            case "d16": return R.drawable.d16;
            case "d17": return R.drawable.d17;
            case "d18": return R.drawable.d18;
            case "d19": return R.drawable.d19;
            case "d20": return R.drawable.d20;
            case "d21": return R.drawable.d21;
            case "d22": return R.drawable.d22;
            case "d23": return R.drawable.d23;
            case "d24": return R.drawable.d24;
            case "d25": return R.drawable.d25;
            case "d26": return R.drawable.d26;
            case "d27": return R.drawable.d27;
            case "d28": return R.drawable.d28;
            case "d29": return R.drawable.d29;
            case "d30": return R.drawable.d30;
            case "d31": return R.drawable.d31;
            case "d53": return R.drawable.d53;
            case "d301": return R.drawable.d301;
            case "d302": return R.drawable.d302;

            case "n00": return R.drawable.n00;
            case "n01": return R.drawable.n01;
            case "n02": return R.drawable.n02;
            case "n03": return R.drawable.n03;
            case "n04": return R.drawable.n04;
            case "n05": return R.drawable.n05;
            case "n06": return R.drawable.n06;
            case "n07": return R.drawable.n07;
            case "n08": return R.drawable.n08;
            case "n09": return R.drawable.n09;
            case "n10": return R.drawable.n10;
            case "n11": return R.drawable.n11;
            case "n12": return R.drawable.n12;
            case "n13": return R.drawable.n13;
            case "n14": return R.drawable.n14;
            case "n15": return R.drawable.n15;
            case "n16": return R.drawable.n16;
            case "n17": return R.drawable.n17;
            case "n18": return R.drawable.n18;
            case "n19": return R.drawable.n19;
            case "n20": return R.drawable.n20;
            case "n21": return R.drawable.n21;
            case "n22": return R.drawable.n22;
            case "n23": return R.drawable.n23;
            case "n24": return R.drawable.n24;
            case "n25": return R.drawable.n25;
            case "n26": return R.drawable.n26;
            case "n27": return R.drawable.n27;
            case "n28": return R.drawable.n28;
            case "n29": return R.drawable.n29;
            case "n30": return R.drawable.n30;
            case "n31": return R.drawable.n31;
            case "n53": return R.drawable.n53;
            case "n301": return R.drawable.n301;
            case "n302": return R.drawable.n302;
            case "sunup": return R.drawable.sunup; // 添加日出图标
            case "sundown": return R.drawable.sundown; // 添加日落图标
            default: return R.drawable.d00; // 默认图标
        }
    }

    // 根据中文风向获取对应的角度（0-360度，北为0度，顺时针增加）
//    private float getWindDirectionDegrees(String windDirection) {
//        switch (windDirection) {
//            case "北风":
//                return 0;
//            case "东北风":
//                return 45;
//            case "东风":
//                return 90;
//            case "东南风":
//                return 135;
//            case "南风":
//                return 180;
//            case "西南风":
//                return 225;
//            case "西风":
//                return 270;
//            case "西北风":
//                return 315;
//            default:
//                return 0; // 默认北风
//        }
//    }

    // 更新每小时天气预报
    private void updateHourlyWeather(JsonArray hourlyData, String sunrise, String sunset, JsonObject now) {
        if (hourlyWeatherContainer == null || hourlyData == null) return;

        hourlyWeatherContainer.removeAllViews();
        LayoutInflater inflater = LayoutInflater.from(getContext());

        // 获取当前小时
        int currentHour = java.util.Calendar.getInstance().get(java.util.Calendar.HOUR_OF_DAY);

        // 创建24小时数据映射，key为小时，value为String[]
        java.util.Map<Integer, String[]> hourDataMap = new java.util.HashMap<>();
        for (int i = 0; i < hourlyData.size(); i++) {
            String hourDataStr = hourlyData.get(i).getAsString();
            String[] parts = hourDataStr.split(",");
            if (parts.length < 7) continue;
            // parts[0] 例："13日11时"
            String timeStr = parts[0];
            String hourStr = timeStr.substring(timeStr.indexOf("日") + 1, timeStr.indexOf("时")); // 正确解析小时
            int hour = Integer.parseInt(hourStr);
            hourDataMap.put(hour, parts);
        }

        // 解析日出日落时间
        int sunriseHour = Integer.parseInt(sunrise.split(":")[0]);
        int sunriseMinute = Integer.parseInt(sunrise.split(":")[1]);
        int sunsetHour = Integer.parseInt(sunset.split(":")[0]);
        int sunsetMinute = Integer.parseInt(sunset.split(":")[1]);

        // 先显示"现在"
        View nowView = inflater.inflate(R.layout.item_hourly_weather, hourlyWeatherContainer, false);
        TextView tvNowHour = nowView.findViewById(R.id.tvHour);
        ImageView ivNowIcon = nowView.findViewById(R.id.ivWeatherIcon);
        TextView tvNowTemp = nowView.findViewById(R.id.tvTemperature);

        tvNowHour.setText("现在");
        // 使用now对象中的weathercode作为图标代码
        if (now != null && now.has("weathercode")) {
            ivNowIcon.setImageResource(getWeatherIconResId(now.get("weathercode").getAsString()));
        }
        // 使用now对象中的temp作为温度
        if (now != null && now.has("temp")) {
            tvNowTemp.setText(now.get("temp").getAsString() + "°");
        }
        hourlyWeatherContainer.addView(nowView);

        // 辅助方法：判断targetHour是否在prevHour和currHour之间（考虑跨天）
        java.util.function.BiFunction<Integer, Integer, java.util.function.BiPredicate<Integer, Integer>> isBetween =
                (prevHour, currHour) -> (targetHour, ignore) -> {
                    if (prevHour < currHour) {
                        return targetHour > prevHour && targetHour <= currHour;
                    } else if (prevHour > currHour) { // 跨天
                        return targetHour > prevHour || targetHour <= currHour;
                    } else {
                        return false;
                    }
                };

        // 按时间顺序显示所有小时数据
        for (int i = 0; i < 24; i++) {
            int hour = (currentHour + i) % 24;
            int prevHour = (hour - 1 + 24) % 24;

            // 日出插入逻辑
            if (isBetween.apply(prevHour, hour).test(sunriseHour, 0)) {
                View sunriseView = inflater.inflate(R.layout.item_hourly_weather, hourlyWeatherContainer, false);
                TextView tvSunriseHour = sunriseView.findViewById(R.id.tvHour);
                ImageView ivSunriseIcon = sunriseView.findViewById(R.id.ivWeatherIcon);
                TextView tvSunriseTemp = sunriseView.findViewById(R.id.tvTemperature);

                tvSunriseHour.setText(String.format("%02d:%02d", sunriseHour, sunriseMinute));
                ivSunriseIcon.setImageResource(getWeatherIconResId("sunup"));
                tvSunriseTemp.setText("日出");
                hourlyWeatherContainer.addView(sunriseView);
            }

            // 日落插入逻辑
            if (isBetween.apply(prevHour, hour).test(sunsetHour, 0)) {
                View sunsetView = inflater.inflate(R.layout.item_hourly_weather, hourlyWeatherContainer, false);
                TextView tvSunsetHour = sunsetView.findViewById(R.id.tvHour);
                ImageView ivSunsetIcon = sunsetView.findViewById(R.id.ivWeatherIcon);
                TextView tvSunsetTemp = sunsetView.findViewById(R.id.tvTemperature);

                tvSunsetHour.setText(String.format("%02d:%02d", sunsetHour, sunsetMinute));
                ivSunsetIcon.setImageResource(getWeatherIconResId("sundown"));
                tvSunsetTemp.setText("日落");
                hourlyWeatherContainer.addView(sunsetView);
            }

            // 显示该小时天气
            if (hourDataMap.containsKey(hour)) {
                String[] parts = hourDataMap.get(hour);
                View hourView = inflater.inflate(R.layout.item_hourly_weather, hourlyWeatherContainer, false);
                TextView tvHourlyHour = hourView.findViewById(R.id.tvHour);
                ImageView ivHourlyIcon = hourView.findViewById(R.id.ivWeatherIcon);
                TextView tvHourlyTemp = hourView.findViewById(R.id.tvTemperature);

                tvHourlyHour.setText(String.format("%02d时", hour));
                ivHourlyIcon.setImageResource(getWeatherIconResId(parts[1]));
                tvHourlyTemp.setText(parts[3]);
                hourlyWeatherContainer.addView(hourView);
            }
        }
    }

    /**
     * 根据天气状况设置背景图
     * @param weatherCondition 天气状况
     */
    private void setWeatherBackground(String weatherCondition) {
        View rootView = getView();
        if (rootView == null) return;

        int backgroundResId;
        if (weatherCondition.contains("阴")) {
            backgroundResId = R.drawable.bg_yintian;
        } else if (weatherCondition.contains("雨")) {
            backgroundResId = R.drawable.bg_rain;
        } else if (weatherCondition.contains("晴")) {
            backgroundResId = R.drawable.bg_sum;
        } else if (weatherCondition.contains("云")) {
            backgroundResId = R.drawable.bg_duoyun;
        } else if (weatherCondition.contains("雾")) {
            backgroundResId = R.drawable.bg_yintian;
        }else {
            // 默认背景
            backgroundResId = R.drawable.bg_yintian;
        }

        rootView.setBackgroundResource(backgroundResId);
    }

    private void updateCardColors(String weatherCondition) {
        // 根据天气状况设置卡片颜色
        int backgroundColor;
        int textColor;

        if (weatherCondition.contains("晴") || weatherCondition.contains("云")) {
            backgroundColor = Color.parseColor("#598aca");
            textColor = Color.WHITE;
        } else if (weatherCondition.contains("阴") || weatherCondition.contains("雨")) {
            backgroundColor = Color.parseColor("#576170");
            textColor = Color.WHITE;
        } else {
            backgroundColor = Color.parseColor("#576170");
            textColor = Color.WHITE;
        }

        // 更新预警卡片颜色
        if (cardWarning != null) {
            LinearLayout warningLayout = (LinearLayout) cardWarning.getChildAt(0);
            if (warningLayout != null) {
                warningLayout.setBackgroundColor(backgroundColor);
            }
        }

        // 更新其他卡片颜色
        updateCardColor(R.id.card_air_quality, backgroundColor, textColor);
        updateCardColor(R.id.card_hourly_forecast, backgroundColor, textColor);
        updateCardColor(R.id.card_daily_forecast, backgroundColor, textColor);
        updateCardColor(R.id.card_wind, backgroundColor, textColor);
        updateCardColor(R.id.card_precipitation, backgroundColor, textColor);
        updateCardColor(R.id.card_pm25, backgroundColor, textColor);
        updateCardColor(R.id.card_humidity, backgroundColor, textColor);
        updateCardColor(R.id.card_visibility, backgroundColor, textColor);
        updateCardColor(R.id.card_pressure, backgroundColor, textColor);
        updateCardColor(R.id.card_uv, backgroundColor, textColor);
        updateCardColor(R.id.card_clothing, backgroundColor, textColor);
        updateCardColor(R.id.card_sport, backgroundColor, textColor);
        updateCardColor(R.id.card_allergy, backgroundColor, textColor);
        updateCardColor(R.id.card_cold, backgroundColor, textColor);
        updateCardColor(R.id.card_car_wash, backgroundColor, textColor);

        // 更新底部导航栏颜色
        updateBottomNavigationBarColor();
    }

    private void updateCardColor(int cardId, int backgroundColor, int textColor) {
        CardView card = getView().findViewById(cardId);
        if (card != null) {
            card.setCardBackgroundColor(backgroundColor);
            
            // 更新卡片内所有文本的颜色
            ViewGroup cardContent = (ViewGroup) card.getChildAt(0);
            if (cardContent != null) {
                updateTextColor(cardContent, textColor);
            }
        }
    }

    private void updateTextColor(ViewGroup viewGroup, int textColor) {
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            View child = viewGroup.getChildAt(i);
            if (child instanceof TextView) {
                ((TextView) child).setTextColor(textColor);
            } else if (child instanceof ViewGroup) {
                updateTextColor((ViewGroup) child, textColor);
            }
        }
    }

    // 添加更新底部导航栏颜色的方法
    public void updateBottomNavigationBarColor() {
        if (getActivity() instanceof MainActivity) {
            String weatherCondition = tvWeatherCondition.getText().toString();
            int cardColor;
            if (weatherCondition.contains("晴") || weatherCondition.contains("多云")) {
                cardColor = Color.parseColor("#598aca");
            } else {
                cardColor = Color.parseColor("#576170");
            }
            ((MainActivity) getActivity()).updateBottomNavigationBarColor(cardColor);
        }
    }

    private void fetchWeatherDataByLatLng(String lat, String lng) {
        requireActivity().runOnUiThread(() -> {
            if (loadingLayerWeather != null) loadingLayerWeather.setVisibility(View.VISIBLE);
            // 隐藏所有内容区
            if (tvCityName != null) tvCityName.setVisibility(View.INVISIBLE);
            if (tvCurrentTemperature != null) tvCurrentTemperature.setVisibility(View.INVISIBLE);
            if (tvWeatherCondition != null) tvWeatherCondition.setVisibility(View.INVISIBLE);
            // ...如有其他内容区控件也一并隐藏
        });
        new Thread(() -> {
            try {
                String path = "http://getweather.api.bdymkt.com/lundear/weather1d";
                ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.GET, path);
                request.setCredentials("bd0695e091ee4f83a9e4739a5a6dd3d5", "c3e30f7501024ba1aa958007d6377769");
                request.addHeaderParameter("Content-Type", "application/json; charset=utf-8");
                request.addQueryParameter("lat", lat);
                request.addQueryParameter("lng", lng);
                ApiExplorerClient client = new ApiExplorerClient(new AppSigner());
                ApiExplorerResponse response = client.sendRequest(request);
                String json = response.getResult();
                Log.d("定位城市", "Fragment接口原始返回: " + json);
                JSONObject obj = new JSONObject(json);
                JSONObject data = obj.optJSONObject("data");
                String cityName = "";
                String temp = "";
                String weather = "";
                if (data != null) {
                    JSONObject cityInfo = data.optJSONObject("cityInfo");
                    if (cityInfo != null) {
                        cityName = cityInfo.optString("areaCn");
                    }
                    JSONObject now = data.optJSONObject("now");
                    if (now != null) {
                        temp = now.optString("temp");
                        weather = now.optString("weather");
                    }
                }
                final String finalCityName = cityName;
                final String finalTemp = temp;
                final String finalWeather = weather;
                boolean hasWeather = !finalCityName.isEmpty() && !finalTemp.isEmpty() && !finalWeather.isEmpty();
                requireActivity().runOnUiThread(() -> {
                    if (hasWeather) {
                        if (tvCityName != null) {
                            tvCityName.setText(finalCityName);
                            tvCityName.setVisibility(View.VISIBLE);
                        }
                        if (tvCurrentTemperature != null) {
                            tvCurrentTemperature.setText(finalTemp + "°");
                            tvCurrentTemperature.setVisibility(View.VISIBLE);
                        }
                        if (tvWeatherCondition != null) {
                            tvWeatherCondition.setText(finalWeather);
                            tvWeatherCondition.setVisibility(View.VISIBLE);
                        }
                        if (loadingLayerWeather != null) loadingLayerWeather.setVisibility(View.GONE);
                    } else {
                        // 数据不全，loading层一直可见，内容区不显示
                        if (loadingLayerWeather != null) loadingLayerWeather.setVisibility(View.VISIBLE);
                        if (tvCityName != null) tvCityName.setVisibility(View.INVISIBLE);
                        if (tvCurrentTemperature != null) tvCurrentTemperature.setVisibility(View.INVISIBLE);
                        if (tvWeatherCondition != null) tvWeatherCondition.setVisibility(View.INVISIBLE);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "定位城市天气获取失败", Toast.LENGTH_SHORT).show();
                    if (loadingLayerWeather != null) loadingLayerWeather.setVisibility(View.VISIBLE);
                    if (tvCityName != null) tvCityName.setVisibility(View.INVISIBLE);
                    if (tvCurrentTemperature != null) tvCurrentTemperature.setVisibility(View.INVISIBLE);
                    if (tvWeatherCondition != null) tvWeatherCondition.setVisibility(View.INVISIBLE);
                });
            }
        }).start();
    }
}